#ifndef LINK_H
#define LINK_H
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
// 链式定义

typedef struct LNode
{
    ElemType data;
    struct LNode *next;

} LNode, *LinkList;

LinkList ListHeadInsert(LinkList *List)
{
    LNode *s;
    int x;

    // printf("DEBUG:L<%p>\n", L);
    LinkList L = (LinkList)malloc(sizeof(LNode));
    // printf("DEBUG:L<%p>\n", L);

    L->next = NULL;
    scanf("%d", &x);
    while (x != 9999)
    {
        s = (LNode *)malloc(sizeof(LNode));
        s->data = x;
        s->next = L->next;
        L->next = s;
        scanf("%d", &x);
    }
    *List = L;
    return L;
}

void ListToString(LinkList list)
{
    // LinkList list = *List;
    while (list->next != NULL)
    {
        list = list->next;
        printf("%d ", list->data);
    }
    printf("\n");
}
int InitLinkList(LinkList L)
{
    L = (LinkList)malloc(sizeof(LNode));
    if (L != NULL)
    {
        L->next = NULL;
        return OK;
    }
    else
    {
        return ERROR;
    }
}
// O(n)
void CreateList0(LinkList *L)
{
    if (!L)
        InitLinkList(*L);

    LNode *node;
    int x;
    scanf("%d", &x);
    while (x != 9999)
    {
        node = (LNode *)malloc(sizeof(LNode));
        node->data = x;
        node->next = (*L)->next;
        (*L)->next = node;
        scanf("%d", &x);
    }
}
void CreateList1(LinkList *L)
{
    LNode *node;
    int x;
    LNode *r = *L;

    if (!L)
        InitLinkList(*L);

    scanf("%d", &x);
    while (x != 9999)
    {
        node = (LNode *)malloc(sizeof(LNode));
        node->data = x;
        r->next = node;
        r = node;
        scanf("%d", &x);
    }
    r->next = NULL;
}

LNode *GetElem(LinkList L, int i)
{
    int j = 1;
    LNode *p = (L)->next;
    if (i == 0)
        return L;
    if (i < 1)
        return NULL;
    while (p && j < i)
    {
        p = p->next;
        j++;
    }
    return p;
}

LNode *LocateElem(LinkList L, ElemType e)
{
    LNode *p = L->next;
    while (p && p->data != e)
    {
        p = p->next;
    }
    return p;
}
// Insert e into L at i
// 将新值插入到第i个位置
void InsertNode(LinkList L, int i, int e)
{
    LNode *s = (LNode *)malloc(sizeof(LNode));
    s->data = e;
    LNode *p = GetElem(L, i - 1);
    s->next = p->next;
    p->next = s;
}

void DeleteNode(LinkList L, int i)
{
    LNode *p = GetElem(L, i - 1);
    LNode *q = p->next;
    p->next = q->next;
    free(q);
    q = NULL;
}

int ListLength(LinkList L)
{
    LNode *p;
    int i = 0;
    p = L->next;
    while (p)
    {
        i++;
        p = p->next;
    }
    return i;
}
#endif /* LINK_H */